package com.hariro.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hariro.adapter.ListView_Fragment_New_Adapter;
import com.hariro.customview.DropDownListView;
import com.hariro.customview.DropDownListView.OnDropDownListener;
import com.hariro.helptools.HttpClientHelper;
import com.hariro.json.New_Parsejson;
import com.qianfeng.project.R;

public class New_Fragment extends Fragment {

	private DropDownListView dropDownListView;
	private TextView textView_item_popup_hinttime;
	private ImageView imageView_new_refresh;
	private ImageView imageView_new_back;
	private RelativeLayout relativeLayout_fragment;
	private RelativeLayout relativeLayout_details;
	private TextView textView_Tab_new;

	private long thisTime = System.currentTimeMillis();
	private String newstyleURLstart = "http://mobileapi.j.cn/?method=listv4&first=0&start=0&count=10&uid=868033010199109&imgSize=mid2&longitude=4.9E-324&latitude=4.9E-324&thisTime=";
	private String newstyleURLend = "&lastTime=1408344494&freshRecord=iHPxU8U%3D%0A&v=2.0&termId=0&pid=&tid=&shopId=&net=wifi";
	private String jsonString = "";
	private List<Map<String, Object>> totalList = null;
	private String afterJsonString = "";

	private ListView_Fragment_New_Adapter adapter = null;
	private New_Parsejson new_parsejson = null;
	private Handler handler = null;

	private PopupWindow popupWindow;
	private View popupView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 加载数据;
		initData();

		final View view = inflater.inflate(R.layout.fragment_new, null);
		dropDownListView = (DropDownListView) view
				.findViewById(R.id.dropDownListView_new);
		imageView_new_refresh = (ImageView) view
				.findViewById(R.id.imageView_new_refresh);
		imageView_new_back = (ImageView) view
				.findViewById(R.id.imageView_new_back);
		relativeLayout_fragment = (RelativeLayout) view
				.findViewById(R.id.relativeLayout_fragment);
		relativeLayout_details = (RelativeLayout) view
				.findViewById(R.id.relativeLayout_details);
		textView_Tab_new = (TextView) view.findViewById(R.id.textView_Tab_new);

		popupView = inflater
				.inflate(R.layout.popup_fragment_new_hinttime, null);
		textView_item_popup_hinttime = (TextView) popupView
				.findViewById(R.id.textView_item_popup_hinttime);

		// 初始化popupWindow;
		popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		imageView_new_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// FragmentTransaction transaction = getActivity()
				// .getSupportFragmentManager().beginTransaction();
				// Fragment fragment = new New_Detail_Fragment();
				// transaction.replace(R.id.relativeLayout_details,
				// fragment, "100");
				// // mHolder.textView_new_title.setText("宝贝详情");
				// transaction.commit();

				imageView_new_refresh.setVisibility(View.VISIBLE);
				imageView_new_back.setVisibility(View.GONE);
				relativeLayout_fragment.setVisibility(View.VISIBLE);
				relativeLayout_details.setVisibility(View.GONE);
				textView_Tab_new.setText("每日新款");
			}
		});

		// 给刷新图片设置单击监听器;
		imageView_new_refresh.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initData();
				// should call onDropDownComplete function of DropDownListView
				// at end of drop down complete.
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"MM-dd HH:mm:ss");
				// 加载完成后取消加载动画。必须写在 adapter.notifyDataSetChanged();后面
				dropDownListView
						.onDropDownComplete(getString(R.string.update_at)
								+ dateFormat.format(new Date()));
				textView_item_popup_hinttime
						.setText(new New_Parsejson().UPDATE_INFO);
				popupWindow.showAtLocation(popupView, Gravity.TOP, 0, 38);
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(1500);
							popupWindow.dismiss();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
				adapter.notifyDataSetChanged();
				// 加载完成取消 加载动画
				dropDownListView.onBottomComplete();
			}
		});

		dropDownListView.setOnDropDownListener(new OnDropDownListener() {
			@Override
			public void onDropDown() {
				new GetDataTask(true).execute();
			}
		});

		// set on bottom listener
		dropDownListView.setOnBottomListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new GetDataTask(false).execute();
			}
		});

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					adapter = new ListView_Fragment_New_Adapter(getActivity(),
							totalList, view);
					dropDownListView.setAdapter(adapter);
				}
			}
		};
		return view;
	}

	private void initData() {
		// TODO Auto-generated method stub
		new_parsejson = new New_Parsejson();
		jsonString = newstyleURLstart + thisTime + newstyleURLend;
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				totalList = new_parsejson.parserDataToList(jsonString);
				Log.i("--------------->", totalList.size() + "");
				handler.sendEmptyMessage(0);
			}
		}).start();
	}

	private class GetDataTask extends
			AsyncTask<Void, Void, List<Map<String, Object>>> {

		private boolean isDropDown;

		public GetDataTask(boolean isDropDown) {
			this.isDropDown = isDropDown;
		}

		@SuppressWarnings("unused")
		@Override
		protected List<Map<String, Object>> doInBackground(Void... params) {
			List<Map<String, Object>> bottomlist = new ArrayList<Map<String, Object>>();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			long thistime = Long.parseLong(totalList.get(totalList.size() - 1)
					.get("timeStamp").toString());
			afterJsonString = newstyleURLstart + thistime + newstyleURLend;
			String data = new String(
					HttpClientHelper.loadByteFromURL(afterJsonString));
			if (data != null) {
				try {
					JSONObject jsonObject = new JSONObject(data);
					JSONArray itemList = jsonObject.getJSONArray("itemList");
					for (int i = 1; i < itemList.length(); i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						JSONObject objitem = itemList.getJSONObject(i);
						if (!objitem.getString("showAt").equals("0")) {
							map.put("url", objitem.getString("imgUrl"));
							map.put("typeName", objitem.getString("typeName"));
							map.put("title", objitem.getString("shareTitle"));
							map.put("timeStamp", objitem.getString("timeStamp"));
							map.put("itemId", objitem.getString("itemId"));
							map.put("picHeight", objitem.getString("picHeight"));
							map.put("picWidth", objitem.getString("picWidth"));
							map.put("typeId", objitem.getString("typeId"));
						} else {
							map.put("url", objitem.getString("url"));
							map.put("picHeight", objitem.getString("picHeight"));
							map.put("picWidth", objitem.getString("picWidth"));
							map.put("price", objitem.getString("price"));
							map.put("title", objitem.getString("title"));
							map.put("timeStamp", objitem.getString("timeStamp"));
							map.put("itemId", objitem.getString("itemId"));
							map.put("typeId", objitem.getString("typeId"));
						}
						bottomlist.add(map);
					}
					// return bottomlist;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				Toast.makeText(getActivity(), "网络访问失败！", Toast.LENGTH_SHORT)
						.show();
			}
			return bottomlist;
		}

		@Override
		protected void onPostExecute(List<Map<String, Object>> result) {

			if (isDropDown) {
				// listItems.addFirst("Added after drop down");
				// adapter.notifyDataSetChanged();
				initData();
				// should call onDropDownComplete function of DropDownListView
				// at end of drop down complete.
				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"MM-dd HH:mm:ss");
				// 加载完成后取消加载动画。必须写在 adapter.notifyDataSetChanged();后面
				dropDownListView
						.onDropDownComplete(getString(R.string.update_at)
								+ dateFormat.format(new Date()));
				textView_item_popup_hinttime
						.setText(new New_Parsejson().UPDATE_INFO);
				popupWindow.showAtLocation(popupView, Gravity.TOP, 0, 38);
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							Thread.sleep(1500);
							popupWindow.dismiss();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}).start();
			} else {
				totalList.addAll(result);
				adapter.notifyDataSetChanged();
				// 加载完成取消 加载动画
				dropDownListView.onBottomComplete();
			}

			super.onPostExecute(result);
		}
	}
}
